package cn.luke.basic.services;

import cn.luke.basic.entity.DtoPermission;
import cn.luke.basic.mapper.MapperPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Luke on 2025/3/7 17:06.
 */
@Service
@Transactional
public class ServicePermission extends ServiceImpl<MapperPermission, DtoPermission> implements BaseService<DtoPermission>{


    @Override
    public LambdaQueryWrapper<DtoPermission> fillParams(Map<String, Object> params) {
        return null;
    }

    @Resource
    @Lazy
    private ServiceRole serviceRole;

    /**
     * 查询所有权限列表, 并对角色权限进行选中
     * @return List<DtoPermission>
     */
    public List<DtoPermission> findByRoleId(Long roleId) {
        serviceRole.findCheckById(Math.toIntExact(roleId), true);
        //先查询出所有的权限, 再过滤出所有的父级和子级权限, 并将子级权限转成map
        List<DtoPermission> allList = baseMapper.listByRoleId(roleId);
        List<DtoPermission> list1 = allList.stream().filter(permission -> permission.getPid() == 0).toList();
        List<DtoPermission> list2 = allList.stream().filter(permission -> permission.getPid() != 0).toList();
        Map<Long, List<DtoPermission>> map = list2.stream().collect(Collectors.groupingBy(DtoPermission::getPid));
        //将子级权限添加到父级权限的子级集合中
        list1.forEach(permission -> permission.setSubList(map.get(permission.getId())));
        return list1;
    }

}
